<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */
namespace app\mobile\controller;

use app\BaseController;
use think\App;
use think\facade\Request;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use app\admin\model\FigureUser;
use app\admin\model\FigureVideo;
use app\admin\model\FigureSynthesisAvatar;
use app\admin\model\FigureSynthesisBackground;
use app\admin\model\FigureSynthesisSound;
use app\common\service\ApiService;
use app\admin\model\FigureCloneSet;

/**
 * 视频剪辑操作
 *
 * @author Administrator
 *        
 */
class Synthesis extends BaseController
{

    /**
     * 空列表
     * http://aigc.weijuyunke.cn/mobile/synthesis/getPage
     */
    public function getPage()
    {
        return result(0, 'success', array(
            'list' => [],
            'total' => 0,
            'pindex' => 1,
            'psize' => 10,
            'totalPage' => 0
        ));
    }

    /**
     * 形象新增
     * http://aigc.weijuyunke.cn/mobile/synthesis/avatarAdd
     *
     * @param
     *            uid 用户id
     * @param
     *            name 名称
     * @param
     *            video_url 链接
     */
    public function avatarAdd()
    {
        try {
            
            $uid = input('uid');
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            if (empty(input('name')))
                return result(- 1, 'name不能为空');
            if (empty(input('video_url')))
                return result(- 1, 'video_url不能为空');
            
            if (! $user['is_member']) {
                $tally = sysconfig('tally', 'avatar_high_deduct');
                
                if ($user['balance'] < $tally) {
                    return result(- 2, '点数不足，请充值');
                }
            }
            
            $log_no = getPayNo('ST');
            
            $avatarData = array(
                'log_no' => $log_no,
                'uid' => $uid,
                'name' => input('name'),
                'video_url' => input('video_url'),
                'is_status' => 1
            );
            
            $set = FigureCloneSet::where("id", 1)->find();
            if (isset($set['avatar_high_check']) && $set['avatar_high_check'] == 1) {
                
                $avatar = new FigureSynthesisAvatar();
                $avatar->save($avatarData);
                
                user_balance_used($uid, $log_no, 2, 40);
                
                $avatar->save([
                    'is_status' => 1,
                    'current_status' => 'sent'
                ]);
                return result(0, '上传成功，等待审核');
            } else {
                $apiService = new ApiService();
                $result = $apiService->synthesisAvatarAdd($avatarData);
                
                if (isset($result['code']) && $result['code'] == 1) {
                    
                    $avatar = new FigureSynthesisAvatar();
                    $avatar->save($avatarData);
                    
                    user_balance_used($uid, $log_no, 2, 40);
                    
                    $avatar->save([
                        'is_status' => 2,
                        '_id' => $result['data']['id'],
                        'current_status' => $result['data']['current_status']
                    ]);
                    
                    return result(0, '新增成功', $avatar['id']);
                } else {
                    return result(- 1, $result['msg']);
                }
            }
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 形象列表
     * http://aigc.weijuyunke.cn/mobile/synthesis/avatarList
     *
     * @param
     *            uid 用户id
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function avatarList()
    {
        try {
            $uid = input('uid');
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            
            $where = " uid = {$uid} ";
            
            if (! empty(input('current_status'))) {
                $current_status = input('current_status');
                $where .= " AND current_status = '{$current_status}'";
            }
            
            $total = FigureSynthesisAvatar::where($where)->count();
            if ($total) {
                $list = FigureSynthesisAvatar::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
            } else {
                $list = array();
            }
            
            $totalPage = ceil($total / $psize);
            
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 形象删除
     * http://aigc.weijuyunke.cn/mobile/synthesis/avatarDel
     *
     * @param
     *            uid 用户id
     * @param
     *            avatar_id 形象id
     */
    public function avatarDel()
    {
        try {
            $uid = input('uid');
            $avatar_id = input('avatar_id');
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            $avatar = FigureSynthesisAvatar::where([
                'uid' => $uid,
                'id' => $avatar_id
            ])->find();
            if (empty($avatar)) {
                return result(- 1, '形象不存在');
            }
            
            $avatar->delete();
            
            return result(0, '删除成功');
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 视频生成
     * http://aigc.weijuyunke.cn/mobile/synthesis/generate
     *
     * @param
     *            uid 用户id
     * @param
     *            name 视频标题
     * @param
     *            avatar_id 形象id
     * @param
     *            audio_url 音频链接
     *            
     */
    public function generate()
    {
        try {
            
            $request = $this->request;
            $param = $request->param();
            validate(\app\mobile\validate\Synthesis::class)->check($param);
            
            $uid = $param['uid'];
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            if (empty($param['avatar_id']))
                return result(- 1, 'avatar_id不能为空');
            
            if (empty($param['audio_url']))
                return result(- 1, 'audio_url不能为空');
            
            $avatar = FigureSynthesisAvatar::where([
                'uid' => $uid,
                'id' => $param['avatar_id']
            ])->find();
            if (empty($avatar)) {
                return result(- 1, 'avatar不存在');
            }
            
            $duration = ceil(getDuration(1, $param['audio_url']));
            
            if ($duration == 0) {
                return result(- 1, '音频错误');
            }
            
            $tally = (float) sysconfig('tally', 'video_deduct');
            $money = (float) $tally * $duration;
            
            if (! $user['is_member']) {
                if ($user['balance'] < $money) {
                    return result(- 2, '余额不足，请充值');
                }
            } else {
                if ($user['second_infinite'] == 0 && $user['second'] < $duration && $user['balance'] < $money) {
                    return result(- 2, '余额不足，请充值');
                }
            }
            
            $params = array(
                'uid' => $uid,
                'name' => $param['name'],
                'type' => 1,
                'anchor_type' => 1,
                'avatar_id' => $avatar['id'],
                'audio_src' => $param['audio_url'],
                'duration' => $duration
            );
            
            $apiService = new ApiService();
            $result = $apiService->synthesisGenerate([
                'title' => $param['name'],
                'avatar_id' => $avatar['_id'],
                'audio_url' => $param['audio_url']
            ]);
            
            if (isset($result['code']) && $result['code'] == 1) {
                
                $video = new FigureVideo();
                $video->save($params);
                
                $log_no = getPayNo('VC');
                
                $video->save([
                    '_id' => $result['data']['id'],
                    'current_status' => 'init'
                ]);
                
                user_balance_used($uid, $log_no, 2, 6, $duration);
                
                return result(0, '生成成功');
            } else {
                
                return result(- 1, $result['msg']);
            }
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }
}